// pages/songDetail/songDetail.js
import PubSub from 'pubsub-js'
import moment from 'moment'
import request from '../../../utils/request'
const app = getApp()
Page({
  data: {
    isPlay: false,
    songId: "",
    song: {},
    musicLink: "",
    currentTime: '00:00',
    totalTime: '00:00',
    currentWidth: 0
  },
  onLoad(options) {
    const songId = options.songId
    this.setData({
      songId
    })
    this.getMusicDetail(songId)

    if (app.globalData.isMusicPlay && app.globalData.musicId === songId) {
      this.setData({
        isPlay: true
      })
    }

    this.audioManager = wx.getBackgroundAudioManager()
    this.audioManager.onPlay(() => {
      this.changePlayState(true)
      app.globalData.musicId = songId
    })
    this.audioManager.onTimeUpdate(() => {
      let currentTime = moment(this.audioManager.currentTime * 1000).format('mm:ss')
      let currentWidth = this.audioManager.currentTime / this.audioManager.duration * 450
      this.setData({
        currentTime,
        currentWidth
      })
    })
    this.audioManager.onPause(() => {
      this.changePlayState(false)
    })
    this.audioManager.onStop(() => {
      this.changePlayState(false)
    })
    this.audioManager.onEnded(() => {
      this.handleSwitch()
      this.setData({
        currentWidth: 0,
        currentTime: '00:00'
      })
    })
  },

  handleSwitch(e) {
    let type = e ? e.currentTarget.id : 'next'
    this.audioManager.stop()
    PubSub.subscribe('musicId', (msg, data) => {
      this.getMusicDetail(data)
      this.musicControll(true, data)
      PubSub.unsubscribe('musicId')
    })
    PubSub.publish('switchType', type)
  },
  changePlayState(isPlay) {
    this.setData({
      isPlay
    })
    app.globalData.isMusicPlay = isPlay
  },

  async getMusicDetail(id) {
    try {
      let res = await request("song/detail", {
        ids: id
      })
      let totalTime = moment(res.songs[0].dt).format('mm:ss')
      this.setData({
        song: res.songs[0],
        totalTime
      })
      wx.setNavigationBarTitle({
        title: this.data.song.name
      })
    } catch (error) {
      console.log(error);
    }
  },
  handleMusicPlay() {
    let isPlay = !this.data.isPlay
    const {
      songId,
      musicLink
    } = this.data
    this.musicControll(isPlay, songId, musicLink)
  },
  async musicControll(isPlay, musicId, musicLink) {
    try {
      if (isPlay) {
        if (!musicLink) {
          let musicLinkData = await request('song/url', {
            id: musicId
          })
          musicLink = musicLinkData.data[0].url
          this.setData({
            musicLink
          })
        }
        this.audioManager.src = musicLink
        this.audioManager.title = this.data.song.name
        
      } else {
        this.audioManager.pause()
      }
    } catch (error) {
      console.log(error);
    }

  },

  onShareAppMessage() {},
  onShareTimeline() {}
})